<template>
    <div class="app-container">
        <div v-show="!modifyInfo.visible && !detailInfo.visible
            ">
            <!-- 条件栏 -->
            <div class="filter-wrapper">
                <NewPageFilter v-model:query="filterInfo.query.queryMap" :queryMoreJson="true"
                    :filter-list="filterInfo.searchList" :filter-btn="filterInfo.searchBtn" :clearType="clearType"
                    :slipSelectRequest="slipSelectRequest">
                </NewPageFilter>
            </div>
            <div class="filter-wrapper">
                <NewPageFilter v-model:query="filterInfo.query" :filter-btn="filterInfo.btnList">
                    <template v-slot:filter-excel>
                        <el-button @click="exportExcel()">导出Excel </el-button>
                    </template>
                </NewPageFilter>
                <div class="display-flex">
                    <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
                </div>
            </div>

            <!-- 表格 -->
            <TableContainer :refresh="tableInfo.refresh" :init-curpage="tableInfo.initCurpage" v-model:data="tableInfo.data"
                :api="tableInfo.api" v-model:query="filterInfo.query" :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle" :row-class-name="tableRowClassName" @sortChange="sortChange"
                @handleEvent="handleEvent" @pageInfo="pageInfo">
                <template v-slot:col-orderNo="scope">
                    <span class="slip-edit" v-if="scope.row.orderNo" @click="showDetail(scope.row)">{{ scope.row.orderNo
                    }}</span>
                    <span v-else>{{ scope.row.orderNo || '-' }}</span>
                </template>
            </TableContainer>
        </div>

        <SetPreference v-if="preferenceInfo.visible" v-model:visible="preferenceInfo.visible"
            :searchList="filterInfo.searchList" :fieldList="tableInfo.fieldList"
            :customizeUserVO="filterInfo.query.customizeUserVO" :groupLevelShow="false" @callback="setPreferenceCallback" />
        <AdvancedSearch v-if="advancedSearchInfo.visible" v-model:visible="advancedSearchInfo.visible"
            v-model:formData="advancedSearchInfo.data" :fieldList="tableInfo.fieldList"
            @callback="advancedSearchCallback" />

        <!-- 新增或修改 -->
        <Modify v-if="modifyInfo.visible" v-model:visible="modifyInfo.visible" :title="modifyInfo.title"
            :id="modifyInfo.orderId" :isDisabled="modifyInfo.isDisabled" @returnModify="returnModify" />
        <Detail v-if="detailInfo.visible" v-model:visible="detailInfo.visible" :id="detailInfo.id" @returnBack="getList" />
        <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
    </div>
</template>

<script setup name="purchPlan">
import {
    detetePurchPlan,
    getPurchPlanCustomizeListPage,
    exportPurchPlan,
    methodPurchPlan
} from '@/api/purch.js'
import Modify from './modify'
import Detail from './detail'
import { getBusinessKeyById } from '@/api/flowable'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
    sortArr: [],
    copyQueryMap: {},
    query: {
        sortString: '',
        customizeUserVO: {},
        queryMap: {
            // deptAuth: {
            //     asTbName: 'purch_template',
            //     columnName: 'dept_id',
            //     queryType: 'IN',
            //     queryCategory: 'AND',
            //     value: 'deptAuth',
            // },
        },
    },
    searchList: [],
    searchBtn: [
        { type: 'button', label: '搜索', event: search },
        { type: 'button', label: '高级查询', event: advancedSearchShow },
        { type: 'button', label: '重置', event: clearSearch },
    ],
    btnList: [
        {
            type: 'button',
            label: '新增',
            show: proxy.$permission('purchPlan:add'),
            event: create,
        },
        {
            value: 'excel',
            type: 'slot',
            show: proxy.$permission('purchPlan:excel'),
        },
    ],
})
// 表格相关
const tableInfo = ref({
    refresh: 1,
    initCurpage: 1,
    data: [],
    selections: [],
    fieldList: [],
    handle: {
        fixed: 'right',
        label: '操作',
        width: '90',
        btList: [
            {
                label: '提交',
                event: (row) => handelMethodRequest(row, 'submit'),
                show: proxy.$permission('purchPlan:submit'),
                ifRender: function (row) {
                    return row.status == 1 || row.status == 4
                },
            },
            {
                label: '修改',
                event: update,
                show: proxy.$permission('purchPlan:update'),
                ifRender: function (row) {
                    return row.status == 1 || row.status == 4
                },
            },
            {
                label: '删除',
                popconfirmText: '删除后将改变数据,是否继续？',
                event: del,
                show: proxy.$permission('purchPlan:delete'),
                ifRender: function (row) {
                    return row.status == 1 || row.status == 4
                },
            },
            
            {
                label: '修改申请',
                event: modifyApplication,
                show: proxy.$permission('purchPlan:modifyApplication'),
                ifRender: function (row) {
                    return row.status == 7
                },
            },
            
            {
                label: '批准',
                event: (row) => handelMethodRequest(row, 'approved'),
                show: proxy.$permission('purchPlan:ratify'),
                ifRender: checkIfRenderBtnFlow,
            },
            {
                label: '驳回',
                event: (row) => handelMethodRequest(row, 'reject'),
                show: proxy.$permission('purchPlan:reject'),
                ifRender: checkIfRenderBtnFlow,
            },
            {
                label: '拒绝',
                event: (row) => handelMethodRequest(row, 'refuse'),
                show: proxy.$permission('purchPlan:refuse'),
                ifRender: checkIfRenderBtnFlow,
            },
            {
                label: '撤回',
                event: (row) => handelMethodRequest(row, 'revoke'),
                show: proxy.$permission('purchPlan:revoke'),
                ifRender: ifRenderRevoke,
            },
            {
                label: '销审',
                event: (row) => handelMethodRequest(row, 'cancelCheck'),
                show: proxy.$permission('purchPlan:cancelCheck'),
                ifRender: ifRenderCancelAudit,
            },
        ],
    },
})
const modifyInfo = ref({
    visible: false,
    orderId: '',
    isDisabled: false,
    title: '',
})
const detailInfo = ref({
    visible: false,
    id: '',
})
const preferenceInfo = ref({
    visible: false,
})
const advancedSearchInfo = ref({
    visible: false,
    data: {},
})
//导出excel
const excelPrint = ref({
    type: 'print', // 类型print/excel
    excel: {
        api: exportPurchPlan, // 导出数据接口
        params: {}, // 导出参数
    },
    refresh: null,
})
watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

const clearType = ref(true)
const slipSelectRequest = ref(true)
function ifRenderRevoke(row) {
    return (
        row.status == 2 ||
        (row.status == 7 &&
            proxy.$store.state.permission.systemConfig.allow_purch_plan_approval == 0)
    )
}

function ifRenderCancelAudit(row) {
    return (
        row.status == 7 &&
        proxy.$store.state.permission.systemConfig.allow_purch_plan_approval !== 0
    )
}
// 批准/驳回/拒绝
function checkIfRenderBtnFlow(row) {
    return (
        proxy.$store.state.permission.systemConfig.allow_purch_plan_approval ==
        1 && row.status == 2
    )
}
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
function exportExcel() {
    excelPrint.value.type = 'excel'
    excelPrint.value.excel.params = proxy.$fn.deepClone({
        ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
        ...page.value,
    })
    console.log( excelPrint.value.excel.params)
    excelPrint.value.refresh = Math.random()
}
function tableRowClassName({ row }) {
    let rowId = sessionStorage.getItem('storeRowId')
    if (rowId && row.id === Number(rowId)) {
        return 'check-row'
    }
    return ''
}
function returnModify() {
    if (modifyInfo.value.orderId) {
        getList()
    } else {
        search()
    }
}
async function setPreferenceCallback(obj) {
    updateUserCustomize(obj.customizeUserVO).then((res) => {
        if (res && res.success) {
            getCustomize(!slipSelectRequest.value)
        }
    })
}
function advancedSearchShow() {
    advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
    filterInfo.value.query.queryMap = {}
    let arr = [
        // {
        //     fieldName: 'deptId',
        //     queryType: 'IN',
        //     queryCategory: 'AND',
        //     value: 'deptAuth',
        // },
    ]
    filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
    advancedSearchInfo.value.data = obj.data
    await getList()
    clearType.value = !clearType.value
    filterInfo.value.query.queryMap = proxy.$fn.deepClone(
        filterInfo.value.copyQueryMap
    )
}
// 获取列表
function getList() {
    tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
    // 重置分页
    advancedSearchInfo.value.data = {}
    filterInfo.value.query.queryDtoList = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
}
//新增
function create() {
    modifyInfo.value.title = '新增采购计划'
    modifyInfo.value.orderId = ''
    modifyInfo.value.visible = true
    modifyInfo.value.isDisabled = false
}
// 编辑
function update(row) {
    getBusinessKeyById({
        businessKey: row.orderNo,
        businessType: 'purchPlan',
    }).then((res) => {
        if (res.success) {
        sessionStorage.setItem('storeRowId', row.id)
        if (res.data?.processInstanceId) {
            proxy.$fn.setFlowData(res.data, '', proxy.$route)
        } else {
            toModify(row)
        }
        }
    })
    
}
function toModify(data){
    modifyInfo.value.title = '修改采购计划'
    modifyInfo.value.orderId = data.id
    modifyInfo.value.visible = true
    modifyInfo.value.isDisabled = false
}
// 编辑
function modifyApplication(data) {
    sessionStorage.setItem('storeRowId', data.id)
    modifyInfo.value.title = '修改申请'
    modifyInfo.value.orderId = data.id
    modifyInfo.value.visible = true
    modifyInfo.value.isDisabled = true
}
function del(row) {
    if (row && row.id) {
        remove([row.id])
    } else {
        proxy
            .$confirm('删除后将改变数据,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
            .then(() => {
                let ids = tableInfo.value.selections.map((row) => row.id)
                remove(ids)
            })
    }
}
function remove(ids) {
    console.log(ids)
    detetePurchPlan(ids).then((resp) => {
        if (resp && resp.success) {
            getList()
        }
    })
}
function handelMethodRequest(row = undefined, method) {
    const ids = [row.id]
    if (method === 'submit') {
        let data = {
            flowTaskCommentDto: { approvalType: 'submit' },
            processDefinitionKey: 'purchPlan',
            orderIds: ids,
        }
        methodPurchPlan(data, method).then((resp) => {
            if (resp && resp.success) {
                getList()
            }
        })
    } else if (method === 'reject') {
        proxy
            .$prompt('请输入驳回理由', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: proxy.$fn.maxString200,
                inputErrorMessage: '驳回理由不能超过200字符',
            })
            .then(({ value }) => {
                const data = {
                    id: row.id,
                    orderId: row.id,
                    checkOpt: value,
                }
                methodPurchPlan(data, method).then((resp) => {
                    if (resp && resp.success) {
                        getList()
                    }
                })
            })
    } else if (method === 'refuse') {
        proxy
            .$prompt('请输入拒绝理由', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: proxy.$fn.maxString200,
                inputErrorMessage: '拒绝理由不能超过200字符',
            })
            .then(({ value }) => {
                const data = {
                    id: row.id,
                    orderId: row.id,
                    checkOpt: value,
                }
                methodPurchPlan(data, method).then((resp) => {
                    if (resp && resp.success) {
                        getCustomize()
                    }
                })
            })
    }  else if (method === 'approved') {
        methodPurchPlan({ orderIds: ids }, method).then((resp) => {
            if (resp.success) {
                getList()
            }
        })
    } else {
        methodPurchPlan(ids, method).then((resp) => {
            if (resp.success) {
                getList()
            }
        })
    }
}
function clearSearch() {
    clearType.value = !clearType.value
    advancedSearchInfo.value.data = {}
    filterInfo.value.query.queryMap = proxy.$fn.deepClone(
        filterInfo.value.copyQueryMap
    )
    search()
}

// 触发事件
function handleEvent(event, data) {
    switch (event) {
        // 对表格获取到的数据做处理
        case 'tableCheck':
            tableInfo.value.selections = data
            console.log(tableInfo.value.selections)
            break
    }
}
function sortChange(column) {
    if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
        let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
        filterInfo.value.sortArr = arr
        filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
        getList()
    }
}
function showDetail(row) {
    getBusinessKeyById({
        businessKey: row.orderNo,
        businessType: 'purchPlan',
    }).then((res) => {
        if (res.success) {
        sessionStorage.setItem('storeRowId', row.id)
        if (res.data?.processInstanceId) {
            proxy.$fn.setFlowData(res.data, '', proxy.$route)
        } else {
            detailInfo.value.id = row.id
            detailInfo.value.visible = true
        }
        }
    })
}
function getCustomize(_slipSelectRequest = true) {
    let param = {
        tableKey: 'purchPlanList-com.slip.spd.entity.vo.purch.PurchPlanVO',
    }
    getCustomizeSetting(param).then((res) => {
        if (res && res.success) {
            let data = res.data
            filterInfo.value.query.customizeUserVO = data
            tableInfo.value.fieldList = proxy.$fn.setFieldList(
                tableInfo.value.fieldList,
                data.detail
            )
            let searchInfo = proxy.$fn.setSearchList(
                filterInfo.value.searchList,
                data.detail
            )
            filterInfo.value.query.queryMap = {
                ...searchInfo.queryMap,
                ...filterInfo.value.query.queryMap,
            }
            filterInfo.value.searchList = searchInfo.searchList
            filterInfo.value.searchList.forEach((item) => {
                item.event = search
            })
            filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
                filterInfo.value.query.queryMap
            )
            slipSelectRequest.value = _slipSelectRequest
            tableInfo.value.api = getPurchPlanCustomizeListPage
            getList()
        }
    })
}

let obj = {
    orderNo: {
        label: '计划单号',
        value: 'orderNo',
        type: 'slot',
        componentType: 'input',
        show: false,
        hidden: true,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'purch_plan_status',
      show: false,
      hidden: true,
    },
    sumAmount: {
        label: '总金额',
        value: 'sumAmount',
        componentType: 'price',
        type: 'column',
        formatter: proxy.$fn.TripartiteMethod,
        permission: !proxy.$permission('purchPlan:price'),
        show: false,
        hidden: true,
    },
}
tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
